import React, { useCallback, useEffect, useState } from 'react';
import { Button, Icon, Layout, List, message } from 'antd';
import _ from 'lodash';
import {
  downloadAssetForm,
  exportAssetForm,
  getAMatrixList,
  getBMatrixList,
  getSitesByIPMatrix
} from '@api/asset';
import MyECharts from '@components/my-echarts';
import { BMatrixDefaultOption } from './echartsOptions';
import './index.less';
import DetailMatrix from '@containers/ip-matrix/components/detail-matrix/DetailMatrix';
import selectedImg from '@images/play-blue.svg';
import unselectImg from '@images/play.svg';

const { Sider, Content, Header } = Layout;
const prefix = 'ip-matrix';
const IPMatrix = () => {
  const [AMatrixList, setAMatrixList] = useState([]);
  const [BEchartsOptions, setBEchartsOptions] = useState(BMatrixDefaultOption);
  const [options, setOptions] = useState(BMatrixDefaultOption);
  const [displayMatrix, setDisplayMatrix] = useState('');
  const [type, setType] = useState('matrix');
  const [detail, setDetail] = useState({ name: '', sites: [] });
  const [pathList, setPathList] = useState([]);

  const handleGetBMatrixList = matrix => {
    const { _id, name } = matrix;
    getBMatrixList(_id).then(res => {
      const matrixList = _.get(res, 'data.data.matrixList', []);
      // 构建echarts数据
      const echartsData = matrixList.map(item => {
        const { name, siteCount: BSiteCount, _id: BMatrixOid, matrixChildren } = item;

        return {
          name: `${name}(${BSiteCount}个)`,
          orgName: name,
          value: 100,
          level: 'B',
          id: BMatrixOid,
          CMatrixList: matrixChildren
        };
      });
      _.set(options, 'series.0.data', echartsData);
      _.set(options, 'series.0.name', name);
      setPathList([name]);
      setType('matrix');
      setBEchartsOptions(_.cloneDeep(options));
      setOptions(options);
      setDisplayMatrix(_id);
    });
  };

  // 初始化加载
  useEffect(() => {
    getAMatrixList().then(res => {
      const matrixList = _.get(res, 'data.data.matrixList', []);
      setAMatrixList(matrixList);
      if (matrixList.length) {
        handleGetBMatrixList(matrixList[0]);
      }
    });
    // eslint-disable-next-line
  }, []);

  const handleMatrixClick = params => {
    const data = _.get(params, 'data', {});

    const { id, level, name, CMatrixList, orgName } = data;
    if (level === 'B') {
      if (!CMatrixList) {
        return;
      }
      const echartsData = CMatrixList.map(item => {
        const { name, siteCount, _id: CMatrixOid } = item;

        return {
          name: `${name}(${siteCount}个)`,
          orgName: name,
          value: 10,
          level: 'C',
          id: CMatrixOid
        };
      });
      _.set(options, 'series.0.data', echartsData);
      _.set(options, 'series.0.name', name);
      setOptions({ ...options });
      setPathList(list => [...list, orgName]);
    } else if (level === 'C') {
      getSitesByIPMatrix(id).then(res => {
        const sites = _.get(res, 'data.data.sites', []);
        const errMsg = _.get(res, 'data.data.errMsg');
        if (errMsg) {
          message.warning(errMsg);
          return;
        }
        setDetail({ name, sites });
        setType('detail');
        setPathList(list => [...list, orgName]);
      });
    }
  };

  const handlePathPop = () => {
    const newPathList = [...pathList];
    newPathList.pop();
    setPathList(newPathList);
  };

  const handleDetailBackClick = () => {
    setType('matrix');
    handlePathPop();
  };

  const handleSitesExport = useCallback(sites => {
    const siteIds = sites.map(site => site._id);
    exportAssetForm({ query: { siteIds }, sort: { by: 'ipLong' } }).then(res => {
      const fileName = _.get(res, 'data.data.fileName');
      downloadAssetForm(fileName)
        .then()
        .catch();
    });
  }, []);

  const handleMatrixBackClick = () => {
    setOptions(_.cloneDeep(BEchartsOptions));
    handlePathPop();
  };

  return (
    <Layout className={prefix}>
      <Sider className={`${prefix}-sider`} theme="light">
        <div className={`${prefix}-sider-title`}>
          <div>A段 IP</div>
          <div>{AMatrixList.length}</div>
        </div>
        <List
          itemLayout="horizontal"
          dataSource={AMatrixList}
          className={`${prefix}-sider-list`}
          renderItem={item => (
            <List.Item
              className={`${prefix}-sider-list-item ${
                item._id === displayMatrix ? 'active-item' : ''
              }`}
              onClick={() => {
                handleGetBMatrixList(item);
              }}
            >
              <List.Item.Meta title={item.name} description={`${item.siteCount || 0}个`} />
              {item._id === displayMatrix ? (
                <img src={selectedImg} alt="" />
              ) : (
                <img src={unselectImg} alt="" style={{ marginRight: '8px' }} />
              )}
            </List.Item>
          )}
        />
      </Sider>
      <Layout>
        <Content className={`${prefix}-content`}>
          <Header className={`${prefix}-content-header`}>
            <div>
              <h3>IP 矩阵图</h3>
              {pathList.map(path => {
                return <span key={path}>{path}</span>;
              })}
            </div>
            {type === 'detail' && (
              <div>
                <Button onClick={handleDetailBackClick}>
                  <Icon type="rollback" />
                  返回
                </Button>
                <Button type="primary" onClick={() => handleSitesExport(detail.sites)}>
                  <Icon type="export" style={{ color: '#ffffff' }} />
                  导出
                </Button>
              </div>
            )}

            {type === 'matrix' && pathList.length > 1 && (
              <div>
                <Button onClick={handleMatrixBackClick}>
                  <Icon type="rollback" />
                  返回
                </Button>
              </div>
            )}
          </Header>
          {type === 'matrix' ? (
            <MyECharts option={options} onClick={params => handleMatrixClick(params)} />
          ) : (
            <DetailMatrix detail={detail} />
          )}
        </Content>
      </Layout>
    </Layout>
  );
};

IPMatrix.propTypes = {};

export default IPMatrix;
